package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author ZLJ
 * @date 2025/10/11 10:58
 * @Description
 */
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String path=request.getRequestURI();
        log.info("请求路径：{}",path);
        boolean isLoginReq = ObjectUtil.equals(LOGIN_PATH, path);
        if(isLoginReq){
            chain.doFilter(request,response);
            return;
        }
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if(ObjectUtil.isEmpty(token)){
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtil.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("用户名：{}",username);
            Object id=claims.get("id");
            log.info("用户id：{}",id);
            chain.doFilter(request,response);
            return;
        } catch (Exception e) {
            log.error("解析token失败：{}",e.getMessage());
            response.setStatus(401);
            return;
        }
    }
}
